package middlewares

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"mall-api-gin/pkg/util"
	"net/http"
)

func JwtAuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		authHeader := c.Request.Header.Get("token")
		if authHeader == "" {
			c.JSON(http.StatusOK, gin.H{
				"code": 2003,
				"msg":  "请示头中token为空",
			})
			c.Abort()
			return
		}
		fmt.Println("authHeader：", authHeader)
		//fmt.Println(authHeader)
		mc, err := util.ParseToken(authHeader)
		fmt.Println("错误：")
		fmt.Println(err)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 2005,
				"msg":  "无效的token",
			})
			c.Abort()
			return
		}
		c.Set("username", mc.Username)
		c.Next()
	}
}
